package com.example.myapplication.presenter;

import com.example.myapplication.bean.LoginDetailBean;
import com.example.myapplication.contract.ILoginContract;
import com.example.myapplication.net.exception.NewAccountException;
import com.example.myapplication.net.model.IMainModel;
import com.example.myapplication.net.model.MainModeImpl;
import com.example.common.base.INetCallBack;
import com.example.myapplication.slice.LoginAbilitySlice;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * @author geyao
 * @date 2021/7/6
 * des:
 */
public class LoginPresenter implements ILoginContract.Presenter {
    private static final String PHONE_REGEX = "[1][0123456789]\\d{9}";
    private final ILoginContract.View view;
    private final IMainModel mainModel;

    public LoginPresenter(ILoginContract.View view) {
        this.view = view;
        this.mainModel = new MainModeImpl(view.getContext());
    }

    @Override
    public void getPhoneVerifyCode(String phoneNum) {
        if (!phoneNum.matches(PHONE_REGEX)) {
            view.showToast("手机号格式错误");
            return;
        }
        log("ThreadId1: " + Thread.currentThread().getId());
        mainModel.getPhoneVerifyCode(phoneNum, new INetCallBack<Boolean>() {
            @Override
            public void onNext(Boolean bool) {
                view.showToast("验证码发送成功");
            }

            @Override
            public void onError(Exception exception) {
                exception.printStackTrace();
                if (exception instanceof NewAccountException) {
                    view.showNewAccountDialog(phoneNum);
                    return;
                }
                view.showToast("onError: " + exception.getMessage());
            }
        });
    }

    @Override
    public void login(String phoneNum, String verifyCode) {
        if (phoneNum.isEmpty()) {
            view.showToast("请输入手机号");
            return;
        }
        if (verifyCode.isEmpty()) {
            view.showToast("请输入手机验证码");
            return;
        }
        mainModel.login(phoneNum, verifyCode, new INetCallBack<LoginDetailBean>() {
            @Override
            public void onNext(LoginDetailBean bean) {
                log(Thread.currentThread().getId() + " 登录结果" + bean.toString());
                view.showToast("登录成功\n用户名: " + bean.getNetName() + "\ntoken: " + bean.getAccessToken());
            }

            @Override
            public void onError(Exception exception) {
                exception.printStackTrace();
                view.showToast("登录失败");
            }
        });
    }

    private void log(String str) {
        HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, 0x00202, LoginAbilitySlice.class.getSimpleName());
        HiLog.info(hiLogLabel, str);
    }
}
